﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using TNet;

public static class BinaryExtensions
{
    private static Dictionary<byte, object[]> mTemp = new Dictionary<byte, object[]>();

    public static object[] CombineArrays(object obj, params object[] objs)
    {
        int length = objs.Length;
        object[] tempBuffer = GetTempBuffer(length + 1);
        tempBuffer[0] = obj;
        for (int i = 0; i < length; i++)
        {
            tempBuffer[i + 1] = objs[i];
        }
        return tempBuffer;
    }

    private static object[] GetTempBuffer(int count)
    {
        object[] objArray;
        if (!mTemp.TryGetValue((byte) count, out objArray))
        {
            objArray = new object[count];
            mTemp[(byte) count] = objArray;
        }
        return objArray;
    }

    public static object[] ReadArray(this BinaryReader reader)
    {
        int count = reader.ReadInt();
        if (count == 0)
        {
            return null;
        }
        object[] tempBuffer = GetTempBuffer(count);
        for (int i = 0; i < count; i++)
        {
            tempBuffer[i] = reader.ReadObject();
        }
        return tempBuffer;
    }

    public static object[] ReadArray(this BinaryReader reader, object obj)
    {
        int count = reader.ReadInt() + 1;
        object[] tempBuffer = GetTempBuffer(count);
        tempBuffer[0] = obj;
        for (int i = 1; i < count; i++)
        {
            tempBuffer[i] = reader.ReadObject();
        }
        return tempBuffer;
    }

    public static void WriteArray(this BinaryWriter bw, params object[] objs)
    {
        bw.WriteInt(objs.Length);
        if (objs.Length != 0)
        {
            int index = 0;
            int length = objs.Length;
            while (index < length)
            {
                bw.WriteObject(objs[index]);
                index++;
            }
        }
    }
}

